#pragma once

#include <unistd.h>
#include <cstdlib>
#include <iostream>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

const std::string null_chdir = "/dev/null";

void Daemon(int nochdir, int noclose)
{
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    
    if (fork() > 0)
    {
        exit(0);
    }

    if (setsid() < 0)
    {
        std::cerr << "setsid() failure" << std::endl;
        exit(1);
    }

    if (nochdir == 0)
    {
        chdir("/");
    }

    if (noclose == 0)
    {
        int fd = ::open(null_chdir.c_str(), O_RDWR);
        if (fd < 0)
        {
            std::cerr << "open failure" << std::endl;
            exit(1);
        }

        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        close(fd);
    }
}


